
package cn.jinjimi.app.custom.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import cn.jinjimi.base.Task.TaskExecutor;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.DateUtils;
import cn.jinjimi.base.util.LogUtil;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.bean.QuesCode;
import cn.jinjimi.app.controller.CustomerController;
import cn.jinjimi.app.controller.event.AddFollowRecordEvent;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.DeleteFollowRecordEvent;
import cn.jinjimi.app.controller.event.DeleteFollowsRecordPhotosEvent;
import cn.jinjimi.app.controller.event.FollowRecordChangeEvent;
import cn.jinjimi.app.controller.event.PhotoInfoEvent;
import cn.jinjimi.app.controller.event.UpdateFollowsEvent;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.entity.Follow;
import cn.jinjimi.app.custom.ui.adapter.CustomInfoPhotoEditAdapter;
import cn.jinjimi.app.entity.PhotoInfo;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.dialog.DatePickerDialog;
import cn.jinjimi.app.main.dialog.LoadingDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.widget.LunarDatePicker;
import cn.jinjimi.app.util.MultiplePhotoUtils;
import cn.jinjimi.app.util.NetworkUtils;
import cn.jinjimi.app.util.PhotoUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 添加跟进记录
 * 修改
 * 查看
 */
public class AddFollowRecordActivity extends ToolBarCommonActivity implements AdapterView.OnItemClickListener, TextWatcher {

    private GridView mPhotoGradView;
    private CustomInfoPhotoEditAdapter mAdapter;

    private Calendar mEffectDate = null;
    private DatePickerDialog mDateDialog = null;

    private EditText edContent;
    private TextView tvName;
    private TextView tvTime;
    private TextView tvDel;

    private Custom mCustom;
    private Type mCurrentType;  //当前页面的状态:修改或者添加
    private Follow mFollow;

    public enum Type {
        UPDATE,   //修改状态
        ADD       //添加状态
    }

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_add_follow_record);
        setTitle(R.string.add_follow_record);
        mCustom = (Custom) getIntent().getSerializableExtra(BundleKey.PARAM_CUSTOM);
        if (getIntent().getBooleanExtra("isAdd", true)) {
            mCurrentType = Type.ADD;   //true为添加状态
        } else {
            mCurrentType = Type.UPDATE;//false为修改状态
            mFollow = (Follow) getIntent().getSerializableExtra("follows");
        }
        setRightText(R.string.save);
        setRightButtonTextColor(ContextCompat.getColorStateList(AddFollowRecordActivity.this, R.color.btn_comm_green_selector));

        setSwipeEnabled(false);

        TaskExecutor.scheduleTaskOnUiThread(500, new Runnable() {
            @Override
            public void run() {
                setRightBtnEnable(false);
            }
        });
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    public static void launch(Context startActivity, Custom custom, boolean ifOpen, boolean isAdd, Follow follow) {
        if (startActivity == null)
            return;
        Intent intent = new Intent(startActivity, AddFollowRecordActivity.class);
        intent.putExtra("custom", custom);
        intent.putExtra("ifOpen", ifOpen);
        intent.putExtra("follows", follow);
        intent.putExtra("isAdd", isAdd);   //是否添加
        startActivity.startActivity(intent);
    }

    public static void launch(Context startActivity, Custom custom, boolean ifOpen, boolean isAdd) {
        if (startActivity == null)
            return;
        Intent intent = new Intent(startActivity, AddFollowRecordActivity.class);
        intent.putExtra("custom", custom);
        intent.putExtra("ifOpen", ifOpen);
        intent.putExtra("isAdd", isAdd);   //是否添加
        startActivity.startActivity(intent);
    }

    private void initView() {
        tvName = ((TextView) findViewById(R.id.tv_name));
        edContent = (EditText) findViewById(R.id.edt_descr);
        tvTime = (TextView) findViewById(R.id.happen_time);
        mPhotoGradView = (GridView) findViewById(R.id.gridview);
        tvDel = (TextView) findViewById(R.id.txt_delete_folow_record);

        tvTime.setText(DateUtils.formatYYYYMMDDHHmm(System.currentTimeMillis()));
        if (mCurrentType == Type.UPDATE) {
            tvDel.setVisibility(View.VISIBLE);
        } else {
            tvDel.setVisibility(View.GONE);
        }

        if (mCustom == null) {
            tvName.setEnabled(true);
        } else {
            tvName.setText(mCustom.name);
            tvName.setEnabled(false);
        }
    }

    private void initListener() {
        mPhotoGradView.setOnItemClickListener(this);
        tvDel.setOnClickListener(this);
        tvName.setOnClickListener(this);
        edContent.addTextChangedListener(this);
        tvName.addTextChangedListener(this);
        tvTime.addTextChangedListener(this);
        findViewById(R.id.rl_time).setOnClickListener(this);
    }

    private void initData() {
        mAdapter = new CustomInfoPhotoEditAdapter(this);
        mEffectDate = Calendar.getInstance();
        if (mCurrentType == Type.UPDATE) {
            edContent.setText(mFollow.content);
            edContent.setSelection(mFollow.content.length());
            mEffectDate.setTime(new Date(mFollow.time));
            tvTime.setText(DateUtils.formatYYYYMMDDHHmm(mFollow.time));

            if (mFollow.attachments != null) {
                mAdapter.setItems(PhotoInfo.FollowAttachmentParsePhotoInfo(mFollow.attachments));
            }
            setTitle(R.string.custom_follow_record);
        } else {
            setTitle(R.string.add_follow_record);
        }

        int conlum = (AndroidUtils.getWindowWidth(AddFollowRecordActivity.this) - getResources().getDimensionPixelOffset(R.dimen.dp_24)) / getResources().getDimensionPixelSize(R.dimen.dp_75);
        mPhotoGradView.setNumColumns(conlum);
        mPhotoGradView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_time:
                showDatePickerDialog();
                break;
            case R.id.txt_delete_folow_record:
                deleteFollowsDialog();
                break;
            case R.id.tv_name:
                SelectCustomActivity.launch(AddFollowRecordActivity.this, QuesCode.QuestSelectClientCode);
                break;
        }
    }

    @Override
    protected void rightAction() {
        super.rightAction();
        if (mCurrentType == Type.ADD) {
            if (!hasEdit() || StringUtils.isEmpty(edContent.getText().toString())) {
                ToastUtils.toastMessage(AddFollowRecordActivity.this, getString(R.string.please_write_record_content));
            } else if (mCustom == null) {
                ToastUtils.toastMessage(AddFollowRecordActivity.this, getString(R.string.please_select_custom));
            } else
                checkNetTye();
        } else {
            if (!hasEdit())
                ToastUtils.toastMessage(AddFollowRecordActivity.this, getString(R.string.follow_record_content_no_edit));
            else
                checkNetTye();
        }
    }

    /**
     * 检查网络情况 是Wi-Fi还是其他网络
     */
    private void checkNetTye() {
        if (!NetworkUtils.isNetworkConnected(this)) {
            ToastUtils.toastMessage(this, "当前网络不稳定 请稍后再试");
            return;
        }

        if (!NetworkUtils.isWifiAvailable(this) && mAdapter.getUploadItems().size() > 0) {
            getAlertDialog().setTitle("建议您在Wi-Fi网络下再上传图片，可以节省流量哦")
                    .setLeftBtn("取消上传", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getAlertDialog().dismissDialog();
                        }
                    })
                    .setRightBtn("继续上传", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getAlertDialog().dismissDialog();
                            saveAction();
                        }
                    }).showDialog(CommAlertDialog.Style.TWO_BUTTON);

        } else {
            saveAction();
        }

    }

    //保存操作
    @EventTrace(EventID.APP_CUSTOM_ADDFOLLOW_KEEP)
    private void saveAction() {
        if (mCurrentType == Type.ADD) {
            addFollows();
        } else {
            updateFollows();
        }
        //AnalyManager.getInstance().EventThird(AddFollowRecordActivity.this, EventID.CUSTOM_ADDFOLLOW_KEEP);
        //AnalyManager.getInstance().Event(AddFollowRecordActivity.this, EventID.APP_CUSTOM_ADDFOLLOW_KEEP);
    }

    /**
     * 修改跟进记录mEffectTime
     */
    private void updateFollows() {
        if (StringUtils.isEmpty(edContent.getText().toString().trim())) {
            ToastUtils.toastMessage(AddFollowRecordActivity.this, getString(R.string.please_write_record_content));
        } else {
            //设置保存按钮不可按，避免重复提交
            setRightBtnEnable(false);
            LoadingDialog.showForce(this, getString(R.string.custom_update_ing));
            CustomerController.updateFollows(mEffectDate.getTimeInMillis(), mFollow.id, edContent.getText().toString().trim(), mCustom.customerId);
        }

    }

    /**
     * 监听添加跟进记录的数据返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddFollowRecordEvent(AddFollowRecordEvent event) {
        switch (event.state) {
            case DataEvent.SUCC:
                mFollow = event.data.follow;
                if (mAdapter.isEmpty()) {
                    sendFollowRecordChangeEvent();
                    openCustomArchivesActivity();
                } else {
                    mCurrentType = Type.UPDATE;
                    uploadPhotos(mFollow.id, mAdapter.getItems());
                }

                break;
            case DataEvent.FAIL:
                hideLoadingIndicator();
                setRightBtnEnable(true);
                ToastUtils.toastMessage(AddFollowRecordActivity.this, "添加跟进记录失败,请稍后重试");
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateFollowsEvent(UpdateFollowsEvent event) {
        hideLoadingIndicator();
        switch (event.state) {
            case DataEvent.SUCC:
                if (mAdapter.getUploadItems().isEmpty() && StringUtils.isEmpty(mPhotoId)) {
                    sendFollowRecordChangeEvent();
                    ToastUtils.toastMessage(AddFollowRecordActivity.this, getString(R.string.save_success));
                    finish();
                } else {
                    if (StringUtils.isEmpty(mPhotoId)) {
                        if (!mAdapter.getUploadItems().isEmpty()) {
                            uploadPhotos(mFollow.id, mAdapter.getUploadItems());
                        }
                    } else {
                        deleteFollowRecordPhotos(mFollow.id, mPhotoId);
                    }
                }
                break;
            case DataEvent.FAIL:
                setRightBtnEnable(true);
                ToastUtils.toastMessage(AddFollowRecordActivity.this, "修改跟进记录失败,请稍后重试");
                break;

        }
    }

    /**
     * 监听删除跟进记录的数据变化
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteFollowRecordEvent(DeleteFollowRecordEvent event) {
        hideLoadingIndicator();
        switch (event.state) {
            case DataEvent.SUCC:
                sendFollowRecordChangeEvent();
                ToastUtils.toastMessage(AddFollowRecordActivity.this, getString(R.string.delete_success));
                finish();
                break;
            case DataEvent.FAIL:
                setRightBtnEnable(true);
                ToastUtils.toastMessage(AddFollowRecordActivity.this, getString(R.string.delete_fail));
                break;
        }
    }

    /**
     * 删除跟进记录
     */
    private void deleteFollowRecord(String customId, String followId) {
        LoadingDialog.show(this, getString(R.string.deleting_wait));
        CustomerController.deleteFollowRecord(customId, followId);
    }

    /**
     * 弹出删除跟进记录的确定框
     */
    private void deleteFollowsDialog() {
        getAlertDialog().setTitle(getString(R.string.delete))
                .setMessage(getString(R.string.delete_follow_record))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        deleteFollowRecord(String.valueOf(mFollow.customerId), String.valueOf(mFollow.id));
                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    /**
     * 完成添加跟进记录
     */
    private void addFollows() {
        //设置保存按钮不可按，避免重复提交
        setRightBtnEnable(false);
        LoadingDialog.showForce(this, getString(R.string.saving_wait));
        CustomerController.addFollowRecord(mCustom.customerId, edContent.getText().toString().trim(), mEffectDate.getTimeInMillis());
    }

    private void sendFollowRecordChangeEvent() {
        EventBus.getDefault().post(new FollowRecordChangeEvent());
    }

    /* 上传图片 */
    private void uploadPhotos(long ID, final List<PhotoInfo> photoInfos) {


    }

    private void deleteFollowRecordPhotos(long followId, String id) {
        CustomerController.deleteFollowRecordPhotos(String.valueOf(followId), id);
    }

    /**
     * 删除图片后通知跟进记录列表更新
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteFollowsRecordPhotosEvent(DeleteFollowsRecordPhotosEvent event) {
        hideLoadingIndicator();
        switch (event.state) {
            case DataEvent.SUCC:
                mPhotoId = null;
                if (!mAdapter.getUploadItems().isEmpty()) {
                    uploadPhotos(mFollow.id, mAdapter.getUploadItems());
                    return;
                }
                sendFollowRecordChangeEvent();
                openCustomArchivesActivity();

                break;
            case DataEvent.FAIL:
                setRightBtnEnable(true);
                ToastUtils.toastMessage(AddFollowRecordActivity.this, "修改失败,请稍后重试");
                break;
        }

    }

    /**
     * 接收删除图片所需要的ID 和 移除本地图片所需要的id
     *
     * @param event
     */
    private String mPhotoId;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPhotoInfoEvent(PhotoInfoEvent event) {
        if (event.state == PhotoInfoEvent.DELETE) {
            int positon = PhotoInfoEvent.position;
            mAdapter.removeItem(positon);

            if (event.id.equals("0"))
                return;

            if (StringUtils.isEmpty(mPhotoId)) {
                mPhotoId = event.id;
            } else {
                mPhotoId = mPhotoId + "," + event.id;
            }

            setSaveBtnEnable();

            LogUtil.d("跟进记录的ID" + mPhotoId);
        }
    }

    private void showDatePickerDialog() {
        Calendar today = Calendar.getInstance();

        if (mEffectDate != null)
            today = mEffectDate;

        if (mDateDialog == null) {
            mDateDialog = new DatePickerDialog(AddFollowRecordActivity.this,
                    mDatelistener, DatePickerDialog.OnDateSetListener.TYPE_ALL,
                    today.get(Calendar.YEAR),
                    today.get(Calendar.MONTH),
                    today.get(Calendar.DAY_OF_MONTH),
                    today.get(Calendar.HOUR_OF_DAY),
                    today.get(Calendar.MINUTE));
            mDateDialog.hideYearSwitchAndTypeSel();
        }
        mDateDialog.updateDate(
                today.get(Calendar.YEAR),
                today.get(Calendar.MONTH),
                today.get(Calendar.DAY_OF_MONTH),
                today.get(Calendar.HOUR_OF_DAY),
                today.get(Calendar.MINUTE),
                DatePickerDialog.OnDateSetListener.TYPE_ALL);
        mDateDialog.show();
    }

    private DatePickerDialog.OnDateSetListener mDatelistener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(LunarDatePicker view, Calendar date, String dateStr, int type) {
            if (date.getTimeInMillis() > System.currentTimeMillis()) {
                ToastUtils.toastMessage(AddFollowRecordActivity.this, "跟进记录的发生时间不能是未来时间");
            } else {
                mEffectDate = date;
                tvTime.setText(DateUtils.formatYYYYMMDDHHmm(mEffectDate.getTimeInMillis()));
            }
        }
    };

    /* 打开客户档案界面 */
    private void openCustomArchivesActivity() {
        if (getIntent().getBooleanExtra("ifOpen", false)) {
            CustomArchivesActivity.launch(AddFollowRecordActivity.this, mCustom);
        }
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == mAdapter.getItems().size()) {
            PhotoUtils.pickPhoto(AddFollowRecordActivity.this, Constants.MAX_VALUE_PHOTOS - mAdapter.getItems().size());
        }
    }

    private void cancelEditAlert() {
        getAlertDialog().setTitle(getString(R.string.giveup_edit))
                .setMessage(getString(R.string.giveup_edit_msg))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        finish();
                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    /**
     * 是否有修改
     *
     * @return
     */
    private boolean hasEdit() {
        if (mFollow == null) {
            if (StringUtils.isNotEmpty(edContent.getText().toString()))
                return true;

            if (mAdapter.getUploadItems().size() > 0)
                return true;

            return tvName.isEnabled() && mCustom != null;

        } else {
            if (!mFollow.content.equals(edContent.getText().toString())) {
                return true;
            }

            if (mFollow.time != mEffectDate.getTimeInMillis()) {
                return true;
            }
            if (StringUtils.isNotEmpty(mPhotoId)) return true;

            return mAdapter.getUploadItems().size() > 0;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case QuesCode.RequestCodeMultipleAlbum:
                mAdapter.addItems(MultiplePhotoUtils.getInstance().getPhotoList());
                MultiplePhotoUtils.getInstance().clearPhotoList();
                setSaveBtnEnable();
                break;
            case QuesCode.RequestCodeCamera:
                String path = PhotoUtils.handlePhotoResult(AddFollowRecordActivity.this, data, requestCode, resultCode);
                if (null != path) {
                    PhotoInfo photoInfo = new PhotoInfo(path);
                    mAdapter.addItem(photoInfo);
                    MultiplePhotoUtils.getInstance().clearPhotoList();
                    TaskExecutor.scheduleTaskOnUiThread(200, new Runnable() {
                        @Override
                        public void run() {
                            setSaveBtnEnable();
                        }
                    });

                }
                break;
            case QuesCode.QuestSelectClientCode:
                if (data == null)
                    return;
                mCustom = (Custom) data.getSerializableExtra(BundleKey.PARAM_CUSTOM);
                tvName.setText(mCustom.name);
                if (tvName.getText().toString().length() > 10)
                    tvName.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
                else
                    tvName.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        setSaveBtnEnable();
    }

    private void setSaveBtnEnable() {
        if (hasEdit() && mCustom != null && (StringUtils.isNotEmpty(edContent.getText().toString()) || mAdapter.getUploadItems().size() > 0)) {
            setRightBtnEnable(true);
        } else {
            setRightBtnEnable(false);
        }
    }

    @Override
    public void onBackPressed() {
        if (hasEdit()) {
            cancelEditAlert();
        } else {
            super.onBackPressed();
        }
    }
}